package dimension.stock;

import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import java.math.BigInteger;
import java.util.Calendar;

public final class MainClass extends JavaPlugin {

    public static MainClass INSTANCE;
    public static final String PREFIX = "§7[ §c天台证券交易 §7]";
    public static Economy ECONOMY = null;

    private static BukkitTask scheduleTask;

    @Override
    public void onEnable() {
        INSTANCE = this;
        this.getLogger().info("[DimensionStock] 次元股票插件已开启");
        RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
        if(economyProvider == null) {
            throw new RuntimeException("未找到前置Vault");
        }
        if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
            new StockExpansion().register();
        }

        this.getCommand("dst").setExecutor(new Command());
        ECONOMY =economyProvider.getProvider();
        Config.saveDefaultConfig();

        scheduleTask = new BukkitRunnable() {
            @Override
            public void run() {
                if (Calendar.getInstance().get(Calendar.MINUTE)==0 || Calendar.getInstance().get(Calendar.MINUTE)==30) {
                    Exchanger.autoBuySell();
                    MainClass.INSTANCE.getLogger().info("[DimensionStock] 自动调价");
                } else if (Calendar.getInstance().get(Calendar.MINUTE)==0 && Calendar.getInstance().get(Calendar.HOUR_OF_DAY)%12 == 0) {
                    Config.saveLastDayPrice(Config.getLatestPrice());
                    Config.setLastDayVolume(Config.getTodayVolume());
                    Config.setTodayVolume(BigInteger.ZERO);
                    MainClass.INSTANCE.getLogger().info("[DimensionStock] 12小时更新价格");
                }
            }
        }.runTaskTimer(this, 20,20*60);
    }

    @Override
    public void onDisable() {
        scheduleTask.cancel();
        this.getLogger().info("[DimensionStock] 次元股票插件已关闭");
    }
}
